package com.google.bartender;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Gallery;
import android.widget.*;
import android.os.*;
import java.net.*;
import java.io.*;
import android.util.*;

public class ItemSelectionGallery extends Activity implements SensorEventListener {
	private SensorManager mSensorManager;
	private Sensor mRotationVectorSensor;
	private Sensor mShakeSensor;
	private int currentOrientation;
	public String clientMessage = "x";
	public String titleMessage = "Ready...";
	
	private static int ORIENTATION_N = 1;
	private static int ORIENTATION_NW = 3;
	private static int ORIENTATION_W = 4;
	private static int ORIENTATION_SW = 5;
	private static int ORIENTATION_S = 6;
	private static int ORIENTATION_E = 7;

	//public String server_ip = "192.168.145.80";
	public String server_ip = "192.168.144.250";
	public boolean connected = false;
	private long shakeStart = 0;
	private long shakeUnit = 1000000000; // 1000000000 = 1 second.
	private long shakeTimeout = 2*shakeUnit;
	private long putStart = 0;
	private long putUnit = 1000000000; // 1000000000 = 1 second.
	private long putTimeout = 2*shakeUnit;
	private String[] bottleNames = {"Gin", "Rum", "Vodka"};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.itemselectiongallery);

		mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		mRotationVectorSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
		mShakeSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
	    
	    Gallery gallery = (Gallery) findViewById(R.id.gallery);
	    gallery.setAdapter(new ImageAdapter(this));
	    setTitle("Connecting...");
	    Log.d("ClientActivity", "C: Connecting...");
	    Thread cThread = new Thread(new ClientThread());
        cThread.start();
        
        final ItemSelectionGallery g = this;
        
	    gallery.setOnItemSelectedListener(new OnItemSelectedListener()
	    {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				//GameActivity.itemSelected(position);
				clientMessage = "i"+position;
				titleMessage = "Selected '"+bottleNames[position]+"'";
				g.setTitle(titleMessage);
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		
		});
	}
	
	protected void onResume() {
		super.onResume();
		mSensorManager.registerListener(this, mRotationVectorSensor, 10000);	
		mSensorManager.registerListener(this, mShakeSensor, 10000);
	}
	
	protected void onPause() {
		super.onPause();
		mSensorManager.unregisterListener(this);
	}

	/**
	 * See http://developer.android.com/reference/android/hardware/SensorEvent.html for x-y-z directions
	 */
	public void onSensorChanged(SensorEvent event) {
		float[] v = event.values;

		float Sensitive = 11f;
		int newOrientation = currentOrientation;
		String newOrientationS = "";
		
		
		// Shake?
		if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
		{
			if(Math.abs(v[1]) > 15)
			{
				if(shakeStart == 0 || (event.timestamp - shakeStart) > shakeTimeout)
				{
					shakeStart = event.timestamp;
				}
				else
				{
					if((event.timestamp - shakeStart) > shakeUnit)
					{
						//GameActivity.shake();
						clientMessage = "s";
						setTitle("Shaking...");
						shakeStart = 0;
						
					}
				}
			}
			
			return;
		}
		
		// Tilt?
		if (event.sensor.getType() == Sensor.TYPE_GRAVITY) {
			int y = Math.round(v[1]);
			int x = Math.round(v[0]);
			int z = Math.round(v[2]);
			
			if(z <= -9)
			{
				clientMessage = "p";
				Log.d("rotate", "New direction:"+newOrientation+" ("+newOrientationS+")");
				setTitle("Placing drink...");
				return;
			}
			//setTitle(z);
			/*report += "x:"+Math.round(v[0]);
			report += "\ny:"+y;
			report += "\nz:"+z;
*/
			

			if(Math.abs(z) <= 5)
			{
				if(y >= 9)
				{
					newOrientationS = "upright";
					newOrientation = ORIENTATION_N;
				}
				
				if(y <= -9)
				{
					newOrientationS = "upsidedown";
					newOrientation = ORIENTATION_S;
				}
				
				if(y == 0)
				{
					if(x <= -9)
					{
						newOrientationS = "onrightside";
						//newOrientation = ORIENTATION_E;
					}
					else
					{
						newOrientationS = "onleftside";
						//newOrientation = ORIENTATION_W;
					}
				}
				
				if(y > -7 && y < -3)
				{
					newOrientationS = "tilteddown";
					//newOrientation = ORIENTATION_SW;
				}
			}				
		}
		
		if(newOrientation != currentOrientation)
		{
			clientMessage = "o"+newOrientation;
			currentOrientation = newOrientation;
			Log.d("rotate", "New direction:"+newOrientation+" ("+newOrientationS+")");
			setTitle("Pouring...");
			//GameActivity.itemRotated(newOrientation);
		}
	}

	public void onAccuracyChanged(Sensor sensor, int accuracy) {
	}
	public class ClientThread implements Runnable {

        public void run() {
            try {
                InetAddress serverAddr = InetAddress.getByName(server_ip);
                Log.d("ClientActivity", "C: Connecting...");
                Socket socket = new Socket(serverAddr, 8080);
                connected = true;
                setTitle("Connected!");
                GameActivity.connected = true;
                while (connected) {
                    try {
                    	setTitle(titleMessage);
                        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
                                    .getOutputStream())), true);
                        // where you issue the commands
                        out.println(clientMessage);
                        setTitle(titleMessage);
                        
                        
                        clientMessage = "x";
                    } catch (Exception e) {
                        Log.e("ClientActivity", "S: Error", e);
                    }
                }
                GameActivity.connected = false;
                setTitle("Disconnected!");
                socket.close();
                Log.d("ClientActivity", "C: Closed.");
            } catch (Exception e) {
                Log.e("ClientActivity", "C: Error", e);
                connected = false;
            }
        }
    }
}
